package com.ywh.log;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateUtil {
	public final static String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

	public static final String DATE_PART_FORMAT = "yyyy-MM-dd";
	public static final String TIME_PART_FORMAT = "HH:mm:ss.SSS";

	public final static DateFormat default_datetime_format = new SimpleDateFormat(
			DEFAULT_PATTERN);
	public final static DateFormat default_date_format = new SimpleDateFormat(
			DATE_PART_FORMAT);
	public final static DateFormat default_time_format = new SimpleDateFormat(
			TIME_PART_FORMAT);

	/**
	 * 返回当前日期时间
	 * 
	 * @return 例如：2006-06-06 12:12:50
	 */
	public static String getCurDateTime() {
		return getCurDateTime(DEFAULT_PATTERN);
	}

	/**
	 * 在使用频繁的场合，SimpleDateFormat最好new一次 ，做成单件
	 * 
	 * @param formatStr
	 * @param date
	 * @return
	 */
	public static String getUserFormat(String formatStr, Date date) {
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		return format.format(date);
	}

	/**
	 * 格式化日期1
	 * 
	 * @param date
	 * @return yyyy-MM-dd HH:mm:ss
	 */
	public static String format(Date date) {
		return default_datetime_format.format(date);
	}

	public static String format(Timestamp stamp) {
		Date temp = new Date(stamp.getTime());
		return default_datetime_format.format(temp);
	}

	/**
	 * 根据给定的格式返回当前日期或时间 相当于调用getDateTime(formatStr,Calendar.getInstance()
	 * 
	 * @param formatStr
	 *            日期时间格式 例如：yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String getCurDateTime(String formatStr) {
		return getDateTime(formatStr, Calendar.getInstance());
	}

	/**
	 * 根据给定的格式、Calendar返回相应字符串
	 * 
	 * @param formatStr
	 *            日期时间格式 例如：yyyy-MM-dd HH:mm:ss
	 * @param c
	 *            Calendar实例
	 * @return
	 */
	public static String getDateTime(String formatStr, Calendar c) {
		SimpleDateFormat nowDate = new SimpleDateFormat(formatStr);
		String curTimeStr = nowDate.format(c.getTime());

		return curTimeStr;
	}

	/**
	 * 把已经格式好的美国日期转换成指定格式的中国日期
	 * 
	 * @param usFormattedString
	 *            已经格式好的美国日期 例如"02 May 2007"
	 * @param originalPattern
	 *            原始美国日期格式格式 例如"dd MMMMM yyyy"
	 * @param newPattern
	 *            要转换成的中国日期格式 例如"yyyy-MM-dd"
	 * @return 转换后的中国日期格式，如果解析异常即返回原美国日期 此例返回"2007-05-02"
	 */
	public static String usFormat2Ch(String usFormattedString,
			String originalPattern, String newPattern) {
		SimpleDateFormat chFormat = new SimpleDateFormat(newPattern,
				Locale.CHINA);
		SimpleDateFormat usFormat = new SimpleDateFormat(originalPattern,
				Locale.US);
		String convertedString;
		try {
			Date d = usFormat.parse(usFormattedString);
			convertedString = chFormat.format(d);
		} catch (ParseException e) {
			convertedString = usFormattedString;
		}
		return convertedString;
	}

	/**
	 * 把给定的日期字符串解析成对应的Calendar对象
	 * 
	 * @param dateTimeString
	 *            "2007-07-25 12:35:01"
	 * @return
	 */
	public static Long parse(String dateTimeString) {
		DateFormat df = new SimpleDateFormat(TIME_PART_FORMAT);
		Date date = new Date();
		try {
			date = df.parse(dateTimeString);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return date.getTime();
	}

	public static Date parseDate(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_PART_FORMAT);
		try {
			return sdf.parse(dateString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return new Date();
	}

	/**
	 * 返回前天的日期字符串(当前是2007年3月27日，将返回2007-03-25)
	 * 
	 * @return
	 */
	public static String getDayBeforeYesterday() {
		return getBeforeToday(2);
	}

	/**
	 * 返回今天之前几天的日期字符串(当前是2007年3月27日，nDays=5,将返回2007-03-22)
	 * 
	 * @param nDays
	 *            前几天(不大于365,不小于0)
	 * @return
	 */
	public static String getBeforeToday(int nDays) {
		if (nDays < 0) {
			nDays = 0;
		}
		if (nDays > 365) {
			nDays = 365;
		}
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) - nDays);
		SimpleDateFormat nowDate = new SimpleDateFormat("yyyy-MM-dd");
		String timeStr = nowDate.format(c.getTime());

		return timeStr;
	}

	/**
	 * 获得指定日期N天前的日期
	 * 
	 * @param myDate
	 *            指定的日期
	 * @param nDays
	 *            N天
	 * @return N天前的日期
	 */
	public static Date getBeforeDate(Date myDate, int nDays) {
		if (nDays < 0) {
			nDays = 0;
		}
		if (nDays > 365) {
			nDays = 365;
		}
		Calendar c = Calendar.getInstance();
		c.setTime(myDate);
		c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) - nDays);
		return c.getTime();
	}

	/**
	 * 获得昨天的日期 (已去掉时间部分)
	 * 
	 * @return java.util.Date型的日期
	 */
	public static Date getYesterday() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) - 1);
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_PART_FORMAT);
		String day = sdf.format(c.getTime());
		Date date = null;
		try {
			date = sdf.parse(day);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 获取指定日期对应上个月的第一天
	 * 
	 * @param myDate
	 * @return
	 */
	public static Date getLastMonthFristDay(Date myDate) {
		myDate = getDate(myDate);
		Calendar cal = Calendar.getInstance();
		cal.setTime(myDate);
		// 取得当前日期所在月第一天时间对象
		cal.set(Calendar.DAY_OF_MONTH, 1);
		// 日期减一,取得上月最后一天时间对象
		cal.add(Calendar.DAY_OF_MONTH, -1);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		return cal.getTime();

	}

	/**
	 * 获取指定日期对应上个月的最后一天
	 * 
	 * @param myDate
	 * @return
	 */
	public static Date getLastMonthLastDay(Date myDate) {
		myDate = getDate(myDate);
		Calendar cal = Calendar.getInstance();
		cal.setTime(myDate);
		// 取得当前日期所在月第一天时间对象
		cal.set(Calendar.DAY_OF_MONTH, 1);
		// 日期减一,取得上月最后一天时间对象
		cal.add(Calendar.DAY_OF_MONTH, -1);
		return cal.getTime();

	}

	/**
	 * 获得指定Date的日期部分 (已去掉时间部分)
	 * 
	 * @return java.util.Date型的日期
	 */
	public static Date getDate(Date myDate) {
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_PART_FORMAT);
		String day = sdf.format(myDate);
		Date date = null;
		try {
			date = sdf.parse(day);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 获取当月之前nMonths的年月
	 * 
	 * @param nMonths
	 *            2
	 * @return 如果当前年月为2007年12月，则返回2007-10
	 */
	public static String getBeforeMonth(int nMonths) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.MONTH, c.get(Calendar.MONTH) - nMonths);
		SimpleDateFormat nowDate = new SimpleDateFormat("yyyy-MM");
		String timeStr = nowDate.format(c.getTime());

		return timeStr;
	}

	/**
	 * 是否为每月的第一天
	 * 
	 * @return true of false
	 */
	public static boolean isFirstDayOfMonth() {
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.DAY_OF_MONTH) == 1;
	}

	/**
	 * 判断今天是否 为周一
	 * 
	 * @return true or false
	 * @author yaowenhao
	 */
	public static boolean isFirstDayOfWeek() {
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY;
	}

	/**
	 * 获取当前日是当前月的第几天
	 * 
	 * @return
	 */
	public static int getCurDayOfMonth() {
		return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 返回当前年月的第一天第一秒的Date对象
	 * 
	 * @return
	 */
	public static Date getFirstSecondOfCurMonth() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_MONTH, 1);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);

		return c.getTime();
	}

	/**
	 * 返回明天的第一秒的Date对象
	 * 
	 * @return
	 */
	public static Date getFirstSecondOfTomorrow() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, 1);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);

		return c.getTime();
	}

	/**
	 * 返回明天第一秒的毫秒值
	 * 
	 * @return
	 */
	// public static long tomorrowFirstSecondMillis(){
	// Calendar c = Calendar.getInstance();
	// c.add(Calendar.DAY_OF_MONTH,1);
	// c.set(Calendar.HOUR_OF_DAY,0);
	// c.set(Calendar.MINUTE,0);
	// c.set(Calendar.SECOND,0);
	// return c.getTimeInMillis();
	// }

	/**
	 * 获取当前时间至指定钟点数0分0秒时的间隔毫秒数 如果当前钟点大于指定钟点数，则结果是当前时间至第二天指定钟点数0分0秒时的间隔毫秒数
	 * 
	 * @param taskHour
	 *            任务钟点数（5点etc.）
	 * @return
	 */
	public static long betweenTaskHourMillis(int taskHour) {
		if (taskHour < 0) {
			taskHour = 0;
		}
		if (taskHour > 23) {
			taskHour = 23;
		}

		Calendar c = Calendar.getInstance();
		if (c.get(Calendar.HOUR_OF_DAY) >= taskHour) {
			c.add(Calendar.DAY_OF_MONTH, 1);
		}
		c.set(Calendar.HOUR_OF_DAY, taskHour);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		return c.getTimeInMillis() - System.currentTimeMillis();
	}

	/**
	 * 格式化日期时间字符串 如果长度不符就直接返回dateTimeString
	 * 
	 * @param dateTimeString
	 *            (070831123800)
	 * @return (07-08-31 12:38:00)
	 */
	public static String formatDateTime(String dateTimeString) {
		StringBuffer buffer = new StringBuffer(dateTimeString);
		if (buffer.length() != 12) {
			return dateTimeString;
		}
		for (int i = 1; i < 3; i++) {
			buffer.insert(12 - i * 2, ":");
		}
		buffer.insert(6, " ");// 设置日期与时间之间的连字符号
		for (int i = 1; i < 3; i++) {
			buffer.insert(6 - i * 2, "-");// 设置年、月、日之间的连字符号
		}
		return buffer.toString();
	}

	public static int dateDiff(String interval, java.util.Date date1,
			java.util.Date date2) {
		int intReturn = -1000000000;
		if (date1 == null || date2 == null || interval == null)
			return intReturn;
		try {
			java.util.Calendar cal1 = java.util.Calendar.getInstance();
			java.util.Calendar cal2 = java.util.Calendar.getInstance();

			// different date might have different offset
			cal1.setTime(date1);
			long ldate1 = date1.getTime()
					+ cal1.get(java.util.Calendar.ZONE_OFFSET)
					+ cal1.get(java.util.Calendar.DST_OFFSET);

			cal2.setTime(date2);
			long ldate2 = date2.getTime()
					+ cal2.get(java.util.Calendar.ZONE_OFFSET)
					+ cal2.get(java.util.Calendar.DST_OFFSET);

			// Use integer calculation, truncate the decimals
			int hr1 = (int) (ldate1 / 3600000);
			int hr2 = (int) (ldate2 / 3600000);

			int days1 = (int) hr1 / 24;
			int days2 = (int) hr2 / 24;

			int yearDiff = cal2.get(java.util.Calendar.YEAR)
					- cal1.get(java.util.Calendar.YEAR);
			int monthDiff = yearDiff * 12 + cal2.get(java.util.Calendar.MONTH)
					- cal1.get(java.util.Calendar.MONTH);
			int dateDiff = days2 - days1;
			int hourDiff = hr2 - hr1;
			int minuteDiff = (int) (ldate2 / 60000) - (int) (ldate1 / 60000);
			int secondDiff = (int) (ldate2 / 1000) - (int) (ldate1 / 1000);

			if (interval.equals("Y")) {
				intReturn = yearDiff;
			} else if (interval.equals("M")) {
				intReturn = monthDiff;
			} else if (interval.equals("D")) {
				intReturn = dateDiff;
			} else if (interval.equals("H")) {
				intReturn = hourDiff;
			} else if (interval.equals("m")) {
				intReturn = minuteDiff;
			} else if (interval.equals("S")) {
				intReturn = secondDiff;
			}
		} catch (Exception ex) {
		}
		return intReturn;
	}

	/**
	 * 获取距离当前时刻days天之后的时刻
	 * 
	 * @param days
	 * @return
	 */
	public static Date getDateAfterDays(int days) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_YEAR, days);
		return cal.getTime();
	}

	/**
	 * 获取距离当前时刻hours小时之后的时刻
	 * 
	 * @param days
	 * @return
	 */
	public static Date getDateAfterHours(int hours) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR, hours);
		return cal.getTime();
	}

	/**
	 * 获取距离当前时刻minutes分钟之后的时刻
	 * 
	 * @param minutes
	 * @return
	 */
	public static Date getDateAfterMinutes(int minutes) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MINUTE, minutes);
		return cal.getTime();
	}

}
